import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const loginPath = '/login'
const loginPaths = ['/login']
const superAdminRole = 'superadmin'

function hasPermission(roles, routeRoles) {
  if (roles.indexOf(superAdminRole) >= 0) return true
  if (!routeRoles) return true
  return roles.some(role => routeRoles.indexOf(role) >= 0)
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (loginPaths.indexOf(to.path) >= 0) {
    next()
  } else {
    const { token, roles } = store.state.auth
    if (!token || (!token && to.path != loginPath)) {
      // 指定地址不参与逻辑
      if (loginPaths.indexOf(to.path) === -1) {
        next({ path: loginPath })
        NProgress.done()
        return
      }
    }
    if (!hasPermission(roles, to.meta.roles)) {
      next({ path: '/403' })
      NProgress.done()
      return
    }
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})
